package com.yu.gulimall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yu.common.utils.PageUtils;
import com.yu.common.utils.Query;
import com.yu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.yu.gulimall.product.dao.AttrDao;
import com.yu.gulimall.product.dao.AttrGroupDao;
import com.yu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.yu.gulimall.product.entity.AttrEntity;
import com.yu.gulimall.product.entity.AttrGroupEntity;
import com.yu.gulimall.product.entity.CategoryEntity;
import com.yu.gulimall.product.service.AttrGroupService;
import com.yu.gulimall.product.service.CategoryService;
import com.yu.gulimall.product.vo.AttrGroupWithAttrVO;
import com.yu.gulimall.product.vo.AttrInfoVo;
import com.yu.gulimall.product.vo.AttrVo;
import com.yu.gulimall.product.vo.RelationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


@Service("attrGroupService")
@Slf4j
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private CategoryService categoryService;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrDao attrDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils getGroupWithCatelogId(Long catelogId, Map<String, Object> params) {
        String key = (String) params.get("key");
        QueryWrapper<AttrGroupEntity> queryWrapper = new QueryWrapper<>();
        if (catelogId == 0) {
            IPage<AttrGroupEntity> page = this.page(
                    new Query<AttrGroupEntity>().getPage(params),
                    queryWrapper.and((item) -> item.eq("attr_group_id", key).or().like("attr_group_name", key))
            );

            return new PageUtils(page);
        } else {

            queryWrapper.eq("catelog_id", catelogId);
            if (key != null) {
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        queryWrapper.and(
                                (item) -> {
                                    item.eq("attr_group_id", key).or().like("attr_group_name", key);
                                }
                        )
                );
                return new PageUtils(page);
            } else {
                IPage<AttrGroupEntity> page = this.page(
                        new Query<AttrGroupEntity>().getPage(params),
                        queryWrapper
                );
                return new PageUtils(page);
            }

        }


    }

    @Override
    public Long[] findParentPath(Long catelogId) {
        List<Long> cateParentsPath = new ArrayList<>();
        return findPath(catelogId, cateParentsPath);

    }

    @Override
    public List<AttrEntity> getRelationByAttrgroupId(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> attrGroupId = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attIds = attrGroupId.stream().map((item) -> {
            Long attrId = item.getAttrId();
            return attrId;
        }).collect(Collectors.toList());
        if (attIds.size() == 0 || attIds == null) {
            return null;
        }
        return attrDao.selectBatchIds(attIds);
    }

    @Override
    public void deleteWithId(AttrVo[] params) {
        // 先获取所有的属性id
        List<AttrInfoVo> collect = Arrays.stream(params).map((item) -> {
            AttrInfoVo attrInfoVo = new AttrInfoVo();
            BeanUtil.copyProperties(item, attrInfoVo);
            return attrInfoVo;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteByOnce(collect);
    }

    @Override
    public PageUtils getOtherRelationByAttrgroupId(Long attrgroupId, Map<String, Object> params) {
        // TODO: 2024/3/6 未完成 表关系没有滤清
        /**
         *  目的：获取属性分组里面还没有关联的本分类里面的其他基本属性，方便添加新的关联
         */
        // 构造查询条件
        QueryWrapper<AttrGroupEntity> attrGroupEntityQueryWrapper = new QueryWrapper<>();
        attrGroupEntityQueryWrapper.eq("attr_group_id", attrgroupId);
        AttrGroupEntity groupEntity = this.getOne(attrGroupEntityQueryWrapper);
        // 获取三级分类id
        Long catelogId = groupEntity.getCatelogId();
        // 当前属性下的其他分组
        List<AttrGroupEntity> selectList = this.getBaseMapper().selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId).
                ne("attr_group_id", attrgroupId));
        // 获取分组id
        List<Long> attrGroupIds = selectList.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().
                in("attr_group_id", attrGroupIds));
        // 获取其他分组下的全部属性id
        List<Long> attrIdList = relationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        log.info("id{}", attrIdList);


        // 查询关键字
        String key = (String) params.get("key");
        // 构造查询条件
        QueryWrapper<AttrEntity> attrEntityQueryWrapper = new QueryWrapper<>();
        attrEntityQueryWrapper.notIn("attr_id", attrIdList);
        if (StrUtil.isNotBlank(key)) {
            // 关键字不为空
            attrEntityQueryWrapper.and((item) -> {
                item.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        // 分页查询封装
        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(params);
        IPage<AttrEntity> attrEntityIPage = attrDao.selectPage(page, attrEntityQueryWrapper);
        return new PageUtils(attrEntityIPage);
    }

    @Override
    public void addAttrRelation(RelationVO[] relationVOList) {
        List<RelationVO> list = Arrays.asList(relationVOList);
        for (RelationVO relationVO : list) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtil.copyProperties(attrAttrgroupRelationEntity, relationVO);
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public List<AttrGroupWithAttrVO> getAttrgroupWithAttr(Long catelogId) {

        List<AttrGroupEntity> attrGroupEntities = this.list(new QueryWrapper<AttrGroupEntity>().
                eq("catelog_id", catelogId));
        List<AttrGroupWithAttrVO> attrGroupWithAttrVOS = attrGroupEntities.stream().map(item -> {
            AttrGroupWithAttrVO attrGroupWithAttrVO = new AttrGroupWithAttrVO();
            BeanUtil.copyProperties(item, attrGroupWithAttrVO);
            return attrGroupWithAttrVO;
        }).collect(Collectors.toList());
        log.info("信息{}",attrGroupWithAttrVOS);
        for (AttrGroupWithAttrVO attrGroupWithAttrVO : attrGroupWithAttrVOS) {
            Long attrGroupId = attrGroupWithAttrVO.getAttrGroupId();
            List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_group_id", attrGroupId));
            List<Long> collect = relationEntities.stream().map(item -> {
                return item.getAttrId();
            }).collect(Collectors.toList());
            List<AttrEntity> attrEntities = attrDao.selectBatchIds(collect);
            List<AttrVo> attrVos = attrEntities.stream().map(item -> {
                AttrVo attrVo = new AttrVo();
                BeanUtil.copyProperties(item, attrVo);
                return attrVo;
            }).collect(Collectors.toList());
            attrGroupWithAttrVO.setAttrs(attrVos);
        }
        return attrGroupWithAttrVOS;
    }

    private Long[] findPath(Long catelogId, List<Long> cateParentsPath) {
        cateParentsPath.add(catelogId);
        CategoryEntity byId = categoryService.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findPath(byId.getParentCid(), cateParentsPath);
        }
        Collections.reverse(cateParentsPath);
        Long[] pathArray = cateParentsPath.toArray(new Long[0]);
        return pathArray;
    }


}